
package im

import (
    "dhfshop/models"
	"strings"
	"errors"
	"time"
	"github.com/astaxie/beego/orm"
)

//公众号微信消息接收记录表  
type WxMsgReceiptRecords struct {
	WxMsgReceiptRecordId int64 `orm:"column(wx_msg_receipt_record_id);auto"`  //自增主键
	AppId        string    `orm:"column(app_id);size(32);null" json:"app_id"` //托管的公众号ID
	ToUserName   string    `orm:"column(to_user_name);size(50);null"`         //公众号微信号,微信内部产生,比如：gh_38093cc8fd89
	FromUserName string    `orm:"column(from_user_name);size(50);null"`       //发送消息的用户openid
	CreateTime   time.Time `orm:"column(create_time);type(datetime);null"`    //微信端创建时间，因为牵扯时区问题，把整型转换成Time型
	MsgType      string    `orm:"column(msg_type);size(50);null"`             //消息类型是事件
	Event        string    `orm:"column(event);size(50);null"`                      //事件为模板消息发送结束
	MsgBody      string    `orm:"column(msg_body);type(text);null" json:"msg_body"` //存放消息内容或者事件内容(JSON字符串格式)
	/*
	Content      string    `orm:"column(content);size(1000);null"`            //接收文本内容
	
	PicUrl       string    `orm:"column(pic_url);size(512);null"`            //接收图片链接
	MediaId      string    `orm:"column(media_id);size(128);null"`           //接收图片消息媒体ID
	
	Title        string    `orm:"column(title);size(256);null"`               //接收小程序卡片消息标题
	PagePath     string    `orm:"column(page_path);size(256);null"`           //接收小程序卡片消息页面路径
	ThumbUrl     string    `orm:"column(thumb_url);size(512);null"`           //接收小程序卡片消息封面图片的临时CDN链接
	ThumbMediaId string    `orm:"column(thumb_media_id);size(128);null"`      //接收小程序卡片消息封面图片的临时素材id
	
	Reason       string    `orm:"column(reason);type(text);null"`             //审核结果失败的原因,weapp_audit_fail事件需要的字段
	SessionFrom  string    `orm:"column(session_from);size(1000);null"`       //user_enter_tempsession事件需要的字段
	*/
	MsgId        string    `orm:"column(msg_id);size(50);null"`               //消息id
	Status       int16     `orm:"column(status);size(50);null"`               //消息发送状态
	CreatedAt    time.Time `orm:"column(created_at);type(datetime);null"`     //本地创建时间
}

func init() {
    orm.RegisterModel(new(WxMsgReceiptRecords))   
}

func AddWxRecordMessage(m *WxMsgReceiptRecords) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetWxRecordMessageById(id int64) (v *WxMsgReceiptRecords, err error) {
	o := models.GetDefaultDB()
	v = &WxMsgReceiptRecords{WxMsgReceiptRecordId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetWxRecordMessageByAppId(appId string) (v *WxMsgReceiptRecords, err error) {
	o := models.GetDefaultDB()
	v = &WxMsgReceiptRecords{AppId: appId}
	if err = o.Read(v, "AppId"); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllWxRecordMessages(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*WxMsgReceiptRecords, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(WxMsgReceiptRecords))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*WxMsgReceiptRecords
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateWxRecordMessageByAppId(m *WxMsgReceiptRecords, k ...string) (id int64, err error) {
	o := models.GetDefaultDB()
	v := WxMsgReceiptRecords{AppId: m.AppId}
	if err = o.Read(&v, "AppId"); err == nil {
	    m.WxMsgReceiptRecordId = v.WxMsgReceiptRecordId
		if id, err = o.Update(m, k...); err != nil {
		   return
		}
	}
	return
}

func DeleteWxRecordMessageByAppid(appId string) (err error) {
	o := models.GetDefaultDB()
	v := WxMsgReceiptRecords{AppId: appId}
	if err = o.Read(&v, "AppId"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

